// app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

//导入配置
let jwtConfig = require('./config/index');

//导入路由路径
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');


//引入插件
let {expressjwt: jwt} = require('express-jwt')
const bodyParser = require("body-parser");
const pinyinRouter = require("./routes/pinyin");

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//设置跨域
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());

//自定义token验证（中间件）
app.use(jwt({
  secret: jwtConfig.jwt.jwtSecreyKey,
  algorithms: jwtConfig.jwt.algorithms
}).unless({ path: ["/login","/pinyin/getPinyinFirstLetter"] }))

// Token 验证失败处理
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    // Token 无效或过期
    res.status(401).send({
      code: 401,
      msg: 'Token 过期或无效，请重新登录'
    });
  } else {
    next(err);
  }
});


//路由
app.use('/', indexRouter);
app.use('/user', usersRouter);
app.use("/pinyin", pinyinRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  res.send({
    code: err.status || 500,
    msg: err.message
  })
});


module.exports = app;
